package com.labofjet.common.util;

import com.labofjet.common.log.enums.ELogDefine;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * 常用方法
 */
public class CommonUtils {

	private static final ThreadLocal<String> uuidLocal = new ThreadLocal<>();
	/**
	 * 返回LOG的全局traceId
	 *
	 * @param create 没有的话是否创建新的
	 * @return
	 */
	public static String getTraceId(boolean create) {
		HttpServletRequest req = CommonUtils.getCurrentRequest();
		return req == null ? null :
				(req.getHeader(ELogDefine.TRACEID.getCode()) != null ? req.getHeader(ELogDefine.TRACEID.getCode()) :
						create ? UUID.randomUUID().toString() : null);
	}

	public static HttpServletRequest getCurrentRequest() {
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		return requestAttributes == null ? null : requestAttributes.getRequest();
	}

	public static void setTraceId(String s) {
		uuidLocal.set(s);
	}

	public static void removeTraceId() {
		uuidLocal.remove();
	}

	public static String getTraceId() {
		return uuidLocal.get();
	}
}
